package com.h2n.framework.composer;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zul.api.Textbox;
import org.zkoss.zul.api.Button;
import org.zkoss.zul.api.Window;
import org.zkoss.zul.Messagebox;
import org.zkoss.zkplus.spring.SpringUtil;
import com.h2n.framework.dao.IMemberDAO;
import com.h2n.framework.dto.MemberDTO;
import com.h2n.utils.MD5;
import com.h2n.framework.composer.PageConstantsFramework;

/**
 * Created by IntelliJ IDEA.
 * User: NhatNV
 * Date: Jul 30, 2009
 * Time: 12:40:37 AM
 * To change this template use File | Settings | File Templates.
 */
public class LoginComposer extends AbstractPageComposer {
  Textbox txtUserName,txtPassword;
  Button btnLogin;
  Window winForm;
  
  @Override
  public void doAfterCompose(Component component) throws Exception{
    super.doAfterCompose(component);
    txtUserName.focus();
  }

  public void onOK$winForm(Event e) throws Exception {
    try{
      checkMemberLogin();
    }
    catch(Exception ex){
      Messagebox.show(ex.toString(),"Error",Messagebox.OK,Messagebox.INFORMATION);
    }
  }

  public void onClick$btnLogin(Event e) throws Exception{
   try{
      checkMemberLogin();
    }
    catch(Exception ex){
      Messagebox.show(ex.toString(),"Error",Messagebox.OK,Messagebox.INFORMATION);
    }
  }

  private void checkMemberLogin() throws Exception{
    IMemberDAO imemberdao = (IMemberDAO)SpringUtil.getBean("iMemberDao");
    String username = txtUserName.getValue().trim();
    String password = MD5.encrypt(txtPassword.getValue().trim());
    MemberDTO memberdto = imemberdao.getInfo(username,password);
    if(memberdto == null || memberdto.getId() == 0){
      txtUserName.select();
      txtPassword.setText("");
      Messagebox.show("Invalid username or password.","Alert",Messagebox.OK,Messagebox.INFORMATION);
    }
    else{
      session.setAttribute("CurrentMemberLogined",memberdto);
      Executions.sendRedirect(PageConstantsFramework.URL_MASTER_PAGE);
    }
  }
}
